package cn.manjuu.touhou.engine;

import java.util.List;

import android.content.Context;

import cn.manjuu.touhou.APP;
import cn.manjuu.touhou.db.dao.BaseInfoDao;
import cn.manjuu.touhou.db.dao.CardDao;
import cn.manjuu.touhou.domain.BaseInfo;
import cn.manjuu.touhou.domain.Card;
import cn.manjuu.touhou.util.Looger;

/**
 * 处理BaseInfo的业务类
 * 
 * @author 宋疆疆
 * @since 2013.5.22
 */
public class CardEngine {

	private Context mContext;
	private static CardEngine mInstance;
	private CardDao mCardDao;

	public static CardEngine getInstance() {
		if (null == mInstance) {
			mInstance = new CardEngine();
		}
		return mInstance;
	}

	private CardEngine() {
		super();
	}

	public void setContext(Context mContext) {
		this.mContext = mContext;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		mCardDao = new CardDao(mContext);
	}

	/**
	 * 增加一张卡牌
	 * @param cardId
	 * @return
	 */
	public long addCard(int cardId) {
		// TODO Auto-generated method stub
		Card query = mCardDao.query(CardDao.CARD_ID, cardId);
		long result = 0;
		if (null == query) {
			Card card = new Card(BaseInfoEngine.getInstance().getBaseInfo()
					.get_id(), cardId, 1, getCardFileName(cardId));
			result = mCardDao.insert(card);
		} else {
			query.setCount(query.getCount() + 1);
			result = mCardDao.update(CardDao.CARD_ID, query.getCardId(), query);
		}
		Looger.i(APP.ToyMachineFragment, "update card result: " + result);
		if (0 != result) {
			result = BaseInfoEngine.getInstance().reduceMoney(10);
		}
		Looger.i(APP.ToyMachineFragment, "reduceMoney result: " + result);
		return result;
	}

	public String getCardFileName(int nextInt) {
		if (10 > nextInt) {
			return "pari_card_0" + nextInt + ".png";
		} else if (10 <= nextInt) {
			return "pari_card_" + nextInt + ".png";
		}
		return null;
	}

	/**
	 * 获取玩家的所有卡片
	 * @return 
	 */
	public List<Card> getAllCard() {
		// TODO Auto-generated method stub
		List<Card> queryAll = mCardDao.queryAllOrderCardId();
//		for (int i = 0; i < queryAll.size(); i++) {
//			Card card = queryAll.get(i);
//			Looger.i(APP.MainActivity, card.toString());
//		}
		return queryAll;
	}
	
	/**
	 * 获取玩家的所有卡片的id
	 * @return 
	 */
	public List<Long> getAllCardId() {
		// TODO Auto-generated method stub
		List<Long> queryAll = mCardDao.queryAllCardId();
		return queryAll;
	}
	
	/**
	 * 获取玩家拥有的卡牌的最大id
	 * @return
	 */
	public long getCardMaxId() {
		List<Card> allCard = getAllCard();
		long maxId = 0;
		for (Card card : allCard) {
			if(card.getCardId() > maxId) {
				maxId = card.getCardId();
			}
		}
		return maxId;
	}
}
